package cx.zan.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import cx.zan.domain.Product;
import cx.zan.service.ProductService;
import cx.zan.utils.MyBeanUtil;
import cx.zan.utils.RRHolder;
import cx.zan.utils.UUIDUtil;
import cx.zan.utils.UploadUtil;
import cx.zan.vo.ResultVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/4/10 19:28
 */
@WebServlet("/productadd")
public class ProductAddServlet extends HttpServlet {
    private ProductService productService = new ProductService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理数据
        Map<String, String[]> map = UploadUtil.parse(request);

        Product product = new Product();
        MyBeanUtil.populate(product, map);
        //商品id
        product.setPid(UUIDUtil.getId());
        //时间
        product.setPdate(new Date());

        productService.insert(product);

        ResultVo vo = new ResultVo(ResultVo.CODE_FAILED, "添加成功", "请求成功！");

        writeJson(vo);
    }

    //必须每次返回内容个，不管啥 json格式
    public void writeJson(ResultVo resultVo) throws IOException {
        //转json
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(resultVo);
        //System.out.println(resultVo);
        // 难点
        //response.getWriter().print(s);
        RRHolder.getResponse().getWriter().print(s);
    }
}
